package org.emaait.app.action;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.util.Progressable;
import org.apache.log4j.Logger;
import org.emaait.app.util.Common;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class DoUploadAction extends AbstractController{
	private static final Logger LOG=Logger.getLogger(DoUploadAction.class);
    private static final String DEST_LOC="hdfs://namenode1:9000/upload-examcenter/";
    private static int SUM=0;
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		MultipartHttpServletRequest multipartRequest
			=(MultipartHttpServletRequest) request;
		String fileParamName="uploadedfile";
		MultipartFile multipartFile=multipartRequest.getFile(fileParamName);
		
		InputStream in=multipartFile.getInputStream();
		
		String desFileStr=DEST_LOC+System.currentTimeMillis()+"_"+multipartFile.getOriginalFilename();
		LOG.info(desFileStr);
		//File desFile=new File(desFileStr);
		//FileCopyUtils.copy(fileContent, desFile);
		Configuration cfg=new Configuration();
		//cfg.addResource(new Path(""));
		FileSystem fs=FileSystem.get(URI.create(desFileStr), cfg);
		OutputStream out=fs.create(new Path(desFileStr), new Progressable(){
			public void progress() {
				SUM++;
				System.out.print("+");
				if(SUM%50==0){
					System.out.println();
				}
			}
		});
		IOUtils.copyBytes(new BufferedInputStream(in), out, 1024*1, true);
		SUM=0;
		return new ModelAndView("upload");
	}
}